/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tools;

import com.openbrew.openbrewrf.Recipes;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

/**
 *
 * @author dchapman
 */
public class RecipeTools {
    public void checkNameChange(final EntityManager en, final Recipes updatedRecipe){
        final Recipes oldRecipe = getRecipeFromID(en, updatedRecipe.getRid());
        if(!oldRecipe.getRName().equals(updatedRecipe.getRName())){
            //Names have changed change all of the items in the database to the same name.
            List<Recipes> recipes = getRecipesFromName(en, oldRecipe.getRName());
            for(final Recipes recipe : recipes){
                if(recipe.getRid() != updatedRecipe.getRid()){
                    recipe.setRName(updatedRecipe.getRName());
                    en.merge(recipe);
                }
            }
        }
    }
    
    private Recipes getRecipeFromID(final EntityManager en, final int recipeID){
        TypedQuery<Recipes> query = en.createQuery(
                "SELECT r FROM Recipes r WHERE r.rid = ?1", Recipes.class);
        query.setParameter(1, recipeID);
        Recipes recipe = query.getSingleResult();
        return recipe;
    }
    
    private List<Recipes> getRecipesFromName(final EntityManager en, final String name){
        TypedQuery<Recipes> query = en.createQuery(
                "SELECT r FROM Recipes r WHERE r.rName = ?1", Recipes.class);
        query.setParameter(1, name);
        return query.getResultList();
    }
}
